package com.webserver.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应对象
 * 当前类的每一个实例表示给客户端发送的一个HTTP响应内容.每个响应应当包含三部分:
 * 状态行,响应头,响应正文
 */
public class HttpResponse {
    //状态行相关信息
    private int statusCode = 200;//状态代码,默认200
    private String statusReason = "OK";//状态描述
    //响应头相关信息
    private Map<String, String> headers = new HashMap<>();//保存所有响应头
    //响应正文相关信息
    private File entity;//响应正文对应的实体文件

    private Socket socket;

    public HttpResponse(Socket socket) {
        this.socket = socket;
    }

    /**
     * 当前方法用于将当前响应对象内容以标准的响应格式发送给客户端
     */
    public void flush() {
        //1发送状态行
        sendStatusLine();
        //2发送响应头
        sendHeaders();

        //3发送响应正文
        sendContent();

    }

    private void sendStatusLine() {
        try {
            String line = "HTTP/1.1" + " " + statusCode + " " + statusReason;
            println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendHeaders() {
        try {
            //通过遍历headers发送所有的响应头
            headers.forEach((k, v) -> {
                try {
                    println(k + ": " + v);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            //单独发送回车+换行符表示响应头发送完毕了!
            println("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendContent() {
        if (entity!=null) {
            try (
                    FileInputStream fis = new FileInputStream(entity);
            ) {
                OutputStream out = socket.getOutputStream();
                int len;
                byte[] data = new byte[1024 * 10];
                while ((len = fis.read(data)) != -1) {
                    out.write(data, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes("ISO8859-1"));
        out.write(13);//发送一个回车符
        out.write(10);//发送一个换行符
    }

    public File getEntity() {
        return entity;
    }

    /**
     * 向响应对象设置响应正文。设置的同时会根据该正文文件添加对应的响应头：
     * Content-Type和Content-Length
     *
     * @param entity
     */
    public void setEntity(File entity) {
        this.entity = entity;
        System.out.println("资源已找到!" + entity.getName());
        String ext = entity.getName().substring(
                entity.getName().lastIndexOf(".") + 1);
        String type = HttpContext.getMimeType(ext);
        putHeader("Content-Type", type);
        putHeader("Content-Length", entity.length() + "");
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReason() {
        return statusReason;
    }

    public void setStatusReason(String statusReason) {
        this.statusReason = statusReason;
    }

    /**
     * 添加一个响应头
     *
     * @param name  响应头的名字
     * @param value 响应头对应的值
     */
    public void putHeader(String name, String value) {
        this.headers.put(name, value);
    }
}
